frappe.ui.form.on('Subcontracting Receipt', {
	refresh(frm) {
	    if (frm.doc.docstatus == 1){
	        let docname = frm.docname;
	        frappe.db.count('Purchase Invoice', {filters:{subcontracting_receipt: docname}})
	        .then(cnt=>{
                if (! cnt || cnt === 0) {
                    frm.add_custom_button("创建委外采购发票", ()=>{
	                    frappe.call({
        					method: "zelin_subcontract.api.create_purchase_invoice",
        					args:{
        						docname: docname
        					},
        					freeze: true,
        					freeze_message: __("Creating Purchase Invoice..."),
        					callback: function(r) {
        					    if (!r.exc && r.message){
            					    frm.reload_doc();
            					    frappe.msgprint('已创建采购发票 ' + r.message);
        					    }
        					}
        				})
        			})
                }
            })
	    }
	}
})